import pymysql
from flask import jsonify, request
from app.core import db_connect
import uuid
from typing import Optional
from fastapi import APIRouter, Body, HTTPException
from pydantic import BaseModel, Field, ValidationError

router = APIRouter()



# def get_user_by_email(email):
#     db = db_connect.DatabaseConnection()
#     user = db.execute('SELECT * FROM users WHERE email = ?', (email,)).fetchone()
#     conn.close()
#     return user

@router.post("/")
def login():
    """
    Handles a stateful chat request against the knowledge base.
    Uses conversation_id to maintain context.
    """
    # try:
    #     # 手动验证请求数据
    #     request = Introduction_Practice_ChatRequest(**request_data['content'])
    # except ValidationError as e:
    #     # 打印详细的验证错误
    #     print(f"请求数据验证失败: {e.errors()}")
    #     print(f"收到的请求数据: {request_data}")
    #     raise HTTPException(status_code=422, detail=e.errors())
    data = request.get_json()

    # 检查是否包含必要的字段
    if not all(k in data for k in ('email', 'password')):
        return jsonify({'message': '请输入邮箱和密码'}), 400

    email = data['email']
    password = data['password']
    db = db_connect.DatabaseConnection()
    sql = "SELECT * FROM users WHERE email = %s"
    params = (email,)
    try:
        with db.cursor_context() as cursor:
            # 执行查询
            cursor.execute(sql, params)
            # 返回所有结果
            results = cursor.fetchall()
    except pymysql.Error as e:
        print(f"查询执行失败: {e}")
        raise  # 可根据需要选择是否抛出异常
    # 查询用户
    db.disconnect()


    # 验证用户是否存在以及密码是否正确
    if not results:
        return jsonify({'message': '邮箱不存在'}), 401
    if results['password'] != password:  # 直接比较明文密码
        return jsonify({'message': '密码错误'}), 401

    # 登录成功，返回简单信息（不使用token）
    return jsonify({
        'message': '登录成功',
        'email': email  # 返回邮箱用于前端显示
    }), 200